rm(list=ls())
gc()

theme_minimal_panel <- function(base_size = 11, base_family = "",
                          base_line_size = base_size / 22,
                          base_rect_size = base_size / 22) {
  # Starts with theme_bw and remove most parts
  theme_bw(
    base_size = base_size,
    base_family = base_family,
    base_line_size = base_line_size,
    base_rect_size = base_rect_size
  ) %+replace%
    theme(
      axis.ticks      = element_blank(),
      legend.background = element_blank(),
      legend.key        = element_blank(),
      panel.background  = element_blank(),
      panel.border      = element_rect(fill = NA, colour = "black", size = .1),
      strip.background  = element_blank(),
      plot.background   = element_blank(),
      
      complete = TRUE
    )
}


library(Hmisc)
library(tidyverse)
library(ggplot2)
states = tolower(c("AL", "AR", "CA", "CT", "FL", "IL", "IN", "KS", "KY", "MA", "MD",
                   "MO",
                   "NE", "NV", "NY", "OH", "OR", "PA", "RI", "SC", "TN", "TX", "VA", "WA",
                   "WV"))

plt_data = c(NA, NA, NA, NA, NA)
for(state in states){
  f = paste0('rdd_',state,'.Rdata')
    load(f)
    
plt= as.data.frame(
      cbind(rep(as.Date(data$dob),3*8),
            c(data$white, data$black, data$hispanic,
               data$democrat_white, data$democrat_black, data$democrat_hispanic,
             data$republican_white, data$republican_black, data$republican_hispanic,
               data$vote.gen2008_white, data$vote.gen2008_black, data$vote.gen2008_hispanic,
               data$vote.gen2010_white, data$vote.gen2010_black, data$vote.gen2010_hispanic,
               data$vote.gen2012_white, data$vote.gen2012_black, data$vote.gen2012_hispanic,
               data$vote.gen2014_white, data$vote.gen2014_black, data$vote.gen2014_hispanic,
               data$vote.gen2016_white, data$vote.gen2016_black, data$vote.gen2016_hispanic
              ),

            rep(c( rep("white",nrow(data)), rep("black", nrow(data)), rep("hispanic", nrow(data))),8),
            c(rep("Registered",nrow(data)*3),
              rep("Democrat",nrow(data)*3),
              rep("Republican",nrow(data)*3),
              rep("Vote 2008",nrow(data)*3),
              rep("Vote 2010",nrow(data)*3),
              rep("Vote 2012",nrow(data)*3),
              rep("Vote 2014",nrow(data)*3),
              rep("Vote 2016",nrow(data)*3)
              
              )
            
            
            
            )
      
      ,stringsAsFactors = F)
    colnames(plt)= c("dob", "count", "race", "outcome")
    plt$state = state
    plt_data = rbind(plt_data,plt)
    print(state)
  
}
plt_data$dob = as.Date(as.integer(plt_data$dob), origin="1970-01-01")
plt_data=plt_data[-1,]
plt_data$count = as.integer(plt_data$count)
plt_data = as_tibble(plt_data)
fullplt = plt_data %>%
  as_tibble%>%
  group_by(dob, outcome, race) %>% dplyr::summarize(count = sum(count,na.rm=T))

fullplt$cutoff = ifelse(fullplt$dob <= as.Date("1990-11-04"),1,0)
fullplt$running = as.numeric(fullplt$dob - as.Date("1990-11-04"))

the_names=list(
  'Black'="Black",
  'Hispanic'="Hispanic",
  'White'="White",
  'Vote 2008'="Vote 2008",
  'Vote 2010'="Vote 2010",
  'Vote 2012'="Vote 2012",
  'Vote 2014'="Vote 2014",
  'Vote 2016'="Vote 2016"
)
get_label <- function(variable,value){
  return(the_names[value])
}
data=fullplt[!is.na(fullplt$dob) & (fullplt$running >= -365 & fullplt$running <= 365) & fullplt$outcome %in% c("Vote 2008", "Vote 2010", "Vote 2012","Vote 2014", "Vote 2016"),]%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'Hispanic', 'White')))%>%
  group_by(race)%>%
  mutate(ymin = min(count), ymax = max(count),
         outcome = paste(gsub('Vote ','' , outcome), 'Election'))


ggsave(filename = "figures/Fig1.pdf", width = 9, height = 7,
plot = ggplot(data = data,
           mapping=aes(x = dob, y = count, group= factor(cutoff), linetype=race, shape = race))+
  geom_smooth(color="black", span = 1,  fill = "lightgrey")+
  geom_point(alpha=.05,shape=21)+
  geom_vline(xintercept = as.Date("1990-11-04"), linetype = "dashed") + 
  xlab(NULL)+
  ylab('Votes')+
  scale_linetype_manual(values=c('solid', 'dashed', 'dotdash'))+
  scale_x_date(date_breaks = "7 months", date_labels =  "%b \n %Y")+
  theme_minimal_panel()+
 guides(linetype='none')+
  geom_blank(aes(y = ymin)) +
  geom_blank(aes(y = ymax))+
  theme(axis.text.y=element_text(face='bold'), axis.title.y=element_text(face='bold', size =14), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold"), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
   facet_grid(race~outcome, 
             scales = "free_y" 
  ) +
  NULL
)
